package com.toommi.refuse.service.impl;

import com.toommi.refuse.common.enums.VerifyCodeTypeEnum;
import com.toommi.refuse.common.util.GeneratorUtil;
import com.toommi.refuse.service.RedisService;
import com.toommi.refuse.service.VerifyCodeService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @author yangg
 * @since 2019-08-05 12:18
 */
@Service
@AllArgsConstructor
public class VerifyCodeServiceImpl implements VerifyCodeService {

    private RedisService redisService;

    @Override
    public String sendVerifyCode(String phone, int type, int length, long expire) {

        if (StringUtils.isEmpty(phone)) {
            return "";
        }
        if (!VerifyCodeTypeEnum.hasValue(type)) {
            return "";
        }
        String code = GeneratorUtil.messageCode(length);
        //TODO 调用公司发送短信的接口
        //存储验证码至redis

        String key = VerifyCodeTypeEnum.getTypeEnum(type).getKeyEnum().getKey() + phone;

        redisService.set(key, code);
        redisService.expire(key, expire);

        return code;
    }

    @Override
    public boolean checkVerifyCode(String phone, int type, String code) {

        String key = VerifyCodeTypeEnum.getTypeEnum(type).getKeyEnum().getKey() + phone;

        Object o = redisService.get(key, String.class);
        if (o == null) {
            return false;
        }
        String redisCode = String.valueOf(o);

        return redisCode.equals(code);
    }

    @Override
    public void removeCode(String phone, int type) {

        redisService.del(VerifyCodeTypeEnum.getTypeEnum(type).getKeyEnum().getKey() + phone);

    }
}
